﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using tms.Departments.Dto;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.Caching;
using System.Net;
using Microsoft.Extensions.Caching.Distributed;

namespace tms.Departments
{
    [ApiExplorerSettings(GroupName = "v2")]

    public class DepartmentService : CrudAppService<Department, DepartmentDto, Guid, PagedAndSortedResultRequestDto, CreateUpdateDepartmentDto>, IDepartmentService
    {
        private readonly IRepository<Department, Guid> repository;
        private readonly IDistributedCache<DepartmentDto> cache;

        public DepartmentService(
            IRepository<Department, Guid> repository,
            IDistributedCache<DepartmentDto> cache
            ) : base(repository)
        {
            this.repository = repository;
            this.cache = cache;
        }

        public override Task<DepartmentDto> CreateAsync(CreateUpdateDepartmentDto input)
        {
            input.ParentId = Guid.Empty;
            return base.CreateAsync(input);
        }

        public override async Task<DepartmentDto> GetAsync(Guid id)
        {
            return await cache.GetOrAddAsync(
                nameof(DepartmentDto), //缓存键
                async () => await base.GetAsync(id),
                () => new DistributedCacheEntryOptions
                {
                    AbsoluteExpiration = DateTimeOffset.Now.AddHours(1)
                }
            );
        }

        public async Task<DepartmentDto> GetFromCacheAsync()
        {
            return await cache.GetAsync(nameof(DepartmentDto));
        }

        public async Task RemoveFromCacheAsync()
        {
            await cache.RemoveAsync(nameof(DepartmentDto));
        }
    }
}